/**
 * 工具 2016-12-29 Juliana
 */
;(function (W, U) {
    "use strict";
    W.util = {
        isTargetType: function (obj, typeStr) {
            return typeof obj === typeStr || obj === typeStr;
        },
        isUndefined: function (obj) {
            var that = this;
            return that.isTargetType(obj, 'undefined');
        },
        isNullString: function (obj) {
            var that = this;
            if (typeof (obj) === 'string') {
                if (obj.trim() == '') {
                    return true;
                }
            }
            return false;
        },
        //根据参数键获取参数值
        getParameter: function (str, url) {
            var LocString = url || window.document.location.search;
            var rs = new RegExp("(^|)" + str + "=([^&]*)(&|$)", "gi").exec(LocString), tmp;
            if (tmp = rs)return decodeURIComponent(tmp[2]);
            return "";
        },
        isValid: function (obj) {
            var that = this;
            return !that.isUndefined(obj) && obj != null && !that.isNullString(obj);
        },
        getStorage: function (key) {
            var ls = window.localStorage;
            if (ls) {
                var v = ls.getItem(key);
                if (!v) {
                    return;
                }
                if (v.indexOf('obj-') === 0) {
                    v = v.slice(4);
                    return JSON.parse(v);
                } else if (v.indexOf('str-') === 0) {
                    return v.slice(4);
                }
            }
        },
        setStorage: function (key, value) {
            if (arguments.length === 2) {
                var v = value;
                if (typeof v == 'object') {
                    v = JSON.stringify(v);
                    v = 'obj-' + v;
                } else {
                    v = 'str-' + v;
                }
                var ls = window.localStorage;
                if (ls) {
                    ls.setItem(key, v);
                }
            }
        }, removeStorage: function (key) {
            localStorage.removeItem(key);
        },
        serializeForm: function (serializeArray) {
            if (!typeof serializeArray === 'Array') {
                return {};
            } else {
                var ret = {};
                serializeArray.forEach(function (item) {
                    ret[item.name] = item.value || '';
                });
                return ret;
            }
        },
        checkNumber: function (value) {
            var reg = /^\d+$/g;
            if (value != "" && !reg.test(value)) {
                return false;
            }
            return true;
        },
        textareaToHtml: function (str) {
            return str.replace(/\r{0,}\n/g, "<br/>").replace(/\s/g, "&nbsp;");
        }
        ,
        htmlToTextarea: function (str) {
            return str.replace(/<br\/>/g, "\n").replace(/\&nbsp\;/g, " ");
        },
        checkMobile : function (value) {
            var reg = /^1[3-9][0-9]{9}$/;
            if (reg.test(value)) {
                return true;
            } else {
                return false;
            }
        },
        checkFloat : function (value) {
            var reg = /^(([0-9]|([1-9][0-9]{0,9}))((\.[0-9]{1,2})?))$/;
            if (reg.test(value)) {
                return true;
            } else {
                return false;
            }
        },
        checkUserName : function (value) {
            var reg = /^[a-zA-Z]{1}([a-zA-Z0-9]|[_]){1,19}$/;
            if (reg.test(value)) {
                return true;
            } else {
                return false;
            }
        },
        checkEmail : function (value) {
            var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
            if (reg.test(value)) {
                return true;
            } else {
                return false;
            }
        },
        checkQQ : function (value) {
            var reg = /^[1-9][0-9]{4,14}$/;
            if (reg.test(value)) {
                return true;
            } else {
                return false;
            }
        },
        checkPassword : function (value) {
            var reg = /^[a-zA-Z0-9]{6,20}$/;
            if (reg.test(value)) {
                return true;
            } else {
                return false;
            }
        },
        checkLink : function (value) {
            var reg = /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+$/;
            if (reg.test(value)) {
                return true;
            } else {
                return false;
            }
        },
        initWebSocket : function (cb) {
            var path = window.location.host;
            var protocol = window.location.protocol;
            var ws;
            var http;
            if (protocol.indexOf("https:") > -1) {
                http = "https";
                ws = "wss";
            } else {
                http = "http";
                ws = "ws";
            }
            var websocket;
            if ('WebSocket' in window) {
                websocket = new WebSocket(ws + "://" + path +"/web/web/ws.do");
            } else if ('MozWebSocket' in window) {
                websocket = new MozWebSocket(ws + "://" + path +"/web/web/ws.do");
            } else {
                websocket = new SockJS(http + "://" + path +"/web/web/ws/sockjs.do");
            }
            websocket.onopen = function(event) {
                console.log("WebSocket:已连接");
            };
            websocket.onmessage = function(event) {
                cb(event);
            };
            websocket.onerror = function(event) {
                console.log("WebSocket:发生错误 ");
            };
            websocket.onclose = function(event) {
                console.log("WebSocket:已关闭");
                util.initWebSocket(cb);
            }
        },
        strRealLength: function (value) {
            if (!value) {
                return 0;
            }
            var str = value.replace(/[^\u0000-\u00ff]/g,"aa");
            return str.length;
        },
        layerAlertSuccess: function (content, callBack) {
            top.layer.alert(content, {
                icon: 1,
                closeBtn: 0
            }, function (index) {
                if (util.isValid(index)) {
                    top.layer.close(index);
                }
                typeof callBack === 'function' && callBack();
            })
        },
        layerAlertError: function (content, callBack) {
            top.layer.alert(content, {
                icon: 2,
                closeBtn: 0
            }, function (index) {
                if (util.isValid(index)) {
                    top.layer.close(index);
                }
                typeof callBack === 'function' && callBack();
            })
        },
        layerMsgSuccess: function (content, callBack) {
            top.layer.msg(content, {
                icon: 1,
                time: 1500
            }, function (index) {
                if (util.isValid(index)) {
                    top.layer.close(index);
                }
                typeof callBack === 'function' && callBack();
            })
        },
        layerMsgError: function (content, callBack) {
            top.layer.msg(content, {
                icon: 2,
                time: 1500
            }, function (index) {
                if (util.isValid(index)) {
                    top.layer.close(index);
                }
                typeof callBack === 'function' && callBack();
            })
        },
        getTimeMillis: function (date) {
            if (util.isValid(date)) {
                return new Date(date).getTime();
            } else {
                return new Date().getTime();
            }
        },
        //------日期-------//
        //时间戳转字符串
        getDateStr: function (timeStamp) {
            if (!timeStamp)
                return '';
            var d = new Date(timeStamp);
            return d;
        },
        //js函数代码：字符串转换为时间戳
        getDateTimeStamp: function (dateStr) {
            //	return Date.parse(dateStr.replace(/-/gi, "/"));
            var time = strToDate(dateStr);
            time = time.getTime();
            return time;
        },
        //字符串转日期
        strToDate: function (dateStr) {
            if (!util.isValid(dateStr))
                return '';
            return new Date(Date.parse(dateStr.replace(/-/g, "/")));
        },
        /**
         * 几天前，几小时前
         * @param publishTime
         * @returns {*}
         */
        getDateDiff: function (publishTime) {
            var d_minutes, d_hours, d_days, d_second;
            var timeNow = parseInt(new Date().getTime());
            var d;
            d = timeNow - publishTime;
            d_days = parseInt(d / 86400000);
            d_hours = parseInt(d / 3600000);
            d_minutes = parseInt(d / 60000);
            d_second = parseInt(d / 1000);
            if (d_days > 0 && d_days < 4) {
                return d_days + "天前";
            } else if (d_days <= 0 && d_hours > 0) {
                return d_hours + "小时前";
            } else if (d_hours <= 0 && d_minutes > 0) {
                return d_minutes + "分钟前";
            } else if (d_minutes <= 0 && d_second > 0) {
                return "刚刚";
            } else {
                var s = new Date(publishTime);
                return s.getFullYear() + "-" + (s.getMonth() + 1) + "-" + s.getDate() + "";
            }
        },
        //根据毫秒数获取字符串类型时间
        getLocalTimeStr: function (timestamp, getLong) {
            var systemType = api.systemType;
            var newDate = new Date();
            newDate.setTime(timestamp);
            var newyear = newDate.getFullYear();
            var newmonth = newDate.getMonth();
            var newdate = newDate.getDate();
            var nowDate = new Date();
            var nowyear = nowDate.getFullYear();
            var nowmonth = nowDate.getMonth();
            var nowdate = nowDate.getDate();

            function getDateStr() {
                var str = newDate.toLocaleDateString();
                if (systemType == 'ios') {
                    str = str.substring(5);
                }
                if (getLong) {
                    str += " " + getTimeStr();
                }
                return str;
            }

            function getTimeStr() {
                var str = newDate.toLocaleTimeString();
                if (systemType == 'ios') {
                    str = str.substring(5);
                }
                return str;
            }

            if (newyear < nowyear) {
                //返回年月日
                return getDateStr();
            } else {
                if (newmonth < nowmonth) {
                    return getDateStr();
                } else {
                    if (newdate < nowdate) {
                        return getDateStr();
                    } else {
                        return getTimeStr();
                    }
                }
            }
        }
    }
    //---------------------------------------------------
    // 日期格式化
    // 格式 YYYY/yyyy/YY/yy 表示年份
    // MM/M 月份
    // W/w 星期
    // dd/DD/d/D 日期
    // hh/HH/h/H 时间
    // mm/m 分钟
    // ss/SS/s/S 秒
    //---------------------------------------------------
    Date.prototype.Format = function(fmt) {
        var o = {
            "M+" : this.getMonth()+1, //月份
            "d+" : this.getDate(), //日
            "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
            "H+" : this.getHours(), //小时
            "m+" : this.getMinutes(), //分
            "s+" : this.getSeconds(), //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S" : this.getMilliseconds() //毫秒
        };
        var week = {
            "0" : "/u65e5",
            "1" : "/u4e00",
            "2" : "/u4e8c",
            "3" : "/u4e09",
            "4" : "/u56db",
            "5" : "/u4e94",
            "6" : "/u516d"
        };
        if(/(y+)/.test(fmt)){
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        if(/(E+)/.test(fmt)){
            fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);
        }
        for(var k in o){
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt;
    }
}(window, undefined));